<!--
@description    通用评分组件
@author         秦俊强
@email          458112865@qq.com
@create         2020-02-15 13:50
-->


<!-- html start -->
<template>
  <div class="ant-card ant-card-body">

    <!-- 查询区 start -->
    <div class="menu-box">
      <a-row :gutter="10">

        <!-- 右侧菜单 start -->
        <a-col :md="14" :sm="24">
          <div class="query-date" style="margin-top: 5px;">
            <span>评分日期：</span>
            <span>{{this.yearMonthList.val.text}}</span>
           <!-- <a-select v-if="!yearMonthList.loading"
                      :value="yearMonthList.val.text" @change="changeDate" >
              <a-select-option v-for="date in yearMonthList.arr"
                               :key="date.value">{{ date.text }}</a-select-option>
            </a-select>
            <a-select v-else :defaultValue="'数据加载中'" disabled></a-select>-->
          </div>

          <div class="query-type">
            <span>部门类别：</span>
            <a-select :value="departInfo.arr[departInfo.index].text"
                      @change="typeChange">
              <a-select-option v-for="depart in departInfo.arr"
                               :key="depart.value">{{ depart.text }}</a-select-option>
            </a-select>
          </div>

          <div class="query-depart">
            <span>考核部门：</span>
            <a-select v-if="!departInfo.arr[departInfo.index].value"
                      :value="'全部部门'"
                      :notFoundContent="'请选择「部门类别」'"></a-select>

            <a-select v-else :value="departInfo.arr[departInfo.index]['children'][departInfo.chIndex].text"
                      @change="departChange">
              <a-select-option v-for="depart in departInfo.arr[departInfo.index]['children']"
                               :key="depart.value">{{ depart.text }}</a-select-option>
            </a-select>
          </div>
        </a-col>
        <!-- 右侧菜单 end -->

        <!-- 左侧菜单 start -->
        <a-col :md="10" :sm="24">
          <div class="btn-box">
            <a-button @click="getSysConfig">督办事项</a-button>
            <a-button v-if="!disabled.oneKeyScore" :type="'primary'"
                      @click="oneKeyScore">一键评分</a-button>
            <a-button v-if="disabled.oneKeyScore" :disabled="true"
                      title="当前页没有需要评分的项">一键评分</a-button>

           <!-- <a-button v-if="!disabled.saveOrCancel" @click="saveData">保存数据</a-button>
            <a-button v-if="disabled.saveOrCancel" :disabled="true"
                      title="当前页没有修改项">保存数据</a-button>

            <a-button v-if="!disabled.saveOrCancel" @click="cancel">撤消(未保存数据)</a-button>-->

            <a-button @click="kaGradeCalc">得分计算</a-button>
          </div>
        </a-col>
        <!-- 左侧菜单 end -->

      </a-row>
    </div>
    <!-- 查询区 end -->


    <!-- 表格内容区 start -->
    <div class="table-box">
      <!-- 进度 start -->
      <div class="speed-box" v-if="showSpeed()">
        <div class="speed-total">
          <span class="title">总评分项：</span>
          <span class="num">{{ speedInfo.needCount }}</span>
          <span class="unit"> 个</span>
        </div>

        <div class="speed-load">
          <span class="title">待评分项：</span>
          <span class="num">{{ speedInfo.editedCount }}</span>
          <span class="unit"> 个</span>
        </div>
      </div>
      <!-- 进度 end -->

      <!-- 表格数据 start -->
      <div class="table-box">
        <a-table :loading="loading"
                 :scroll="tableData.scroll"
                 :columns="tableData.columns"
                 :dataSource="tableData.dataSource"
                 :pagination="false" @change="onChange">

          <!-- 编辑单元格 -->
         <!-- <template v-for="item in editAttr[k]" :slot="item.key"
                    slot-scope="text, record, index">
            <editable-cell :destroyOnClose="true" :text="text" :inputAttr="item.attr"
                           :rec="record" :k="item.key" :ind="index"
                           :upData="upData" ref="upDatas" />
          </template>-->


          <template :slot="'grade'" slot-scope="text, record, ind">

            <!-- <div @click="switchScoreArr(ind)" style="cursor: pointer;" v-else> -->
            <!-- 移植操作事件 -->
            <div @click="switchEdit(true, record)" style="cursor: pointer;">

              <span>{{ text }}</span>
              <a-icon type="edit" class="editable-cell-icon" title="编辑" />
            </div>
          </template>
          <!-- 评分 end -->

          <!-- 意见 start -->
          <template :slot="'scoreComments'" slot-scope="text, record, ind">
            <div class="comments-box" v-for="(item, index) in text " :key="index">
              <span v-if="text.length > 1">{{ index + 1 }}. </span>
              <span :title="item.title">{{ item.title }}</span>

              <a-tooltip placement="right" :title="item.content">
                <a-icon class="icon-more" type="message"></a-icon>
              </a-tooltip>
            </div>
          </template>
          <!-- 意见 end -->



          <!-- 月份 -->
          <template v-for="item in monthArr" :slot="item"
                    slot-scope="text, record, index">
            <div :class="setClassName(item)">{{ text }}</div>
          </template>

          <!-- 评分参考 -->
          <template :slot="'operation'" slot-scope="text, record">
            <span class="score-ref" @click="showRefModal(record)">双向评分记录</span>
          </template>
        </a-table>
      </div>
      <!-- 表格数据 end -->

      <!-- 分页器 start -->
      <div class="pagination-box">
        <a-pagination :current="queryParam.pageNo"
                      :pageSize="queryParam.pageSize"
                      :total="resData.total"
                      :pageSizeOptions="['20', '30']"
                      @change="changePage"
                      showSizeChanger
                      @showSizeChange="onShowSizeChange"  />
      </div>
      <!-- 分页器 end -->
    </div>
    <!-- 表格内容区 end -->


    <!-- 弹窗 参考评分 start -->
    <a-modal v-model="modalInfo.show"
             :title="modalInfo.title"
             :width="'98%'"
             :maskClosable="false"
             :footer="null">
      <ScoreReference ref="scoreRef" :k="k"
                      :departInfo="modalInfo.departInfo"
                      :date="modalInfo.date"></ScoreReference>
    </a-modal>
    <!-- 弹窗 参考评分 end -->

    <!-- 评分弹窗编辑 start -->
    <a-modal v-model="gradeModalInfo.show"
             :title="gradeModalInfo.title"
             :maskClosable="false"
             :width="'800px'" :destroyOnClose="true" @ok="saveData">
      <div class="loading-box" v-if="gradeModalInfo.loading">
        <a-icon class="icon-loading" type="loading" />
      </div>
      <EditScoreComments :differentiate="gradeModalInfo.differentiate" :editData="gradeModalInfo.date" :show="gradeModalInfo.show"
                         :date="yearMonthList.val.text"></EditScoreComments>
    </a-modal>
    <!-- 评分弹窗编辑 end -->

  </div>
</template>
<!-- html end -->




<!-- js start -->
<script>

  /* 引入 api 接口配置 */
  import { apiConfig } from './api.config.js';

  /* 引入表格配置文件 */
  import { tableConfig, monthArr } from './table.config.js';

  /* 引入编辑单元格组件，用于点击编辑单元格 */
  import EditableCell from '@/components/EditableCell/EditableCell';

  /* 引入通用表格组件 */
  import EditScoreComments from '../../scoring/components/EditScoreComments';

  /* 引入评分参考组件，用于弹窗查看评分参考内容 */
  import ScoreReference from './ScoreReference';



  export default {
    name: "ScoreTabCommon",
    components: { EditableCell, ScoreReference,EditScoreComments },

    props: {
      /**
       * @description       标识是哪个模块页面的表头（必传项）
       * @example           <kpiTableCommon :k="gm"></kpiTableCommon>
       *
       * k = 'gm'           总经理评分
       * k = 'kpi'          绩效汇总评分
       * */
      k: {
        type: String,
        default: ''
      }
    },

    /* 组件参数 */
    data() {
      let _tableConfig = tableConfig(this.k);
      _tableConfig.columns.forEach((item) => {
        if (['totalGrade', 'indexDepartName'].indexOf(item.dataIndex) >= 0) { item.sorter = true; }
      });

      return {
        /* 查询条件信息 */
        queryParam: {
          pageNo: 1,
          pageSize: 20
        },

        /* 年月下拉菜单 */
        yearMonthList: {
          loading: false,
          arr: [],    // 可选择的年月列表
          val: {}   // 已选年月，默认数组第 0 个
        },
        /*督办事项返参*/
        superviseItem:{},

        /* 部门信息 */
        departInfo: {
          arr: [{ text: '全部类型', value: '' }],
          index: 0,
          chIndex: 0
        },

        /* 初始化表格数据 */
        tableData: _tableConfig,

        /* 排序 */
        orderBy: {
          column: '',   // 需要排序的字段
          order: '',    // 倒序用 desc, 升序用 asc
        },

        monthArr: monthArr(),

        /* 源数据，用来对比用户有没有修改 */
        resData: {},

        /* 配置编辑时展示 input 输入框还是 textarea 文本框 */
        editAttr: {
          gm: [
            { name: '评分', attr: 'input', key: 'grade' },
            { name: '评分意见', attr: 'textarea', key: 'indexValueComments' }
          ],

          kpi: [
            { name: '督办得分', attr: 'input', key: 'superviseGrade' },
            { name: '质量改进评分', attr: 'input', key: 'grade' },
            { name: '评分意见', attr: 'textarea', key: 'indexValueComments' }
          ]
        },

        /* 评分进度信息，针对总经理评分 */
        speedInfo: {},

        /* 标记数据是否在加载中 */
        loading: true,

        /* 是否禁用按钮组 */
        disabled: {
          oneKeyScore: true,    // 一键评分按钮
          saveOrCancel: true    // 保存并计算 和 取消编辑按钮
        },

        /* 显示参考评分弹窗 */
        showModal: true,

        /* 参考评分弹窗信息 */
        modalInfo: {
          show: false,
          title: '',
          date: '',
          departInfo: {}
        },
        /* 评分弹窗信息 */
        //differentiate用于角色区分  申嘉文（kpi）  2   孙毅，葛明 0  纪琼霄（gm）  1
        gradeModalInfo: {
          show: false,
          title: '编辑',
          loading: false,
          date: {},
          differentiate:1
        },
      }
    },

    created() {
      /* 获取评分年月 */
      this.yearMonthList.loading = true;
      apiConfig.common.getYearMonthList().then((res) => {
        this.yearMonthList = {
          loading: false,
          arr: res.result,            // 可选年份下拉选项
          val: res.result[0],         // 默认选第 0 项
        }

        this.getIndexGroupOrgs();     // 获取部门菜单
        this.searchQuery();           // 查询数据
      }).catch((error) => {
        this.yearMonthList.loading = false;
        this.$message.error(error.message);
      });
    },

    /* 函数方法 */
    methods: {


      /* 弹窗编辑 */
      switchEdit(b, obj) {
      debugger;
      if (this.k === 'kpi') { this.gradeModalInfo.differentiate = 2 }
        this.gradeModalInfo.date = JSON.parse(JSON.stringify(obj));
        this.gradeModalInfo.loading = false;
        this.gradeModalInfo.show = true;
      },

      /* 监听表格排序的变化 */
      onChange(a, b, c) {
        let orderBy = this.orderBy;
        if (orderBy.column != c.columnKey) {
          orderBy.column = c.columnKey;
          orderBy.order = 'desc';
        } else {
          orderBy.order = (orderBy.order === 'desc') ? 'asc' : 'desc';    // 倒序用 desc, 升序用 asc
        }

        this.searchQuery();
      },

      /* 动态给 class 高亮 */
      setClassName(key) {
        let currentMonthKey = 'm' + this.yearMonthList.val.value.slice(4, 6);
        return (currentMonthKey === key) ? 'high_light' : '';
      },

      /* 获取部门下拉菜单 */
      getIndexGroupOrgs() {
        apiConfig.common.getIndexGroupOrgs().then((res) => {
          let resData = res.result;

          for (let i = 0; i < resData.length; i++) {
            let item = resData[i];
            let param = { text: item.text, value: item.value, children: item.orgs };

            param.children[0].text = '全部部门';
            param.children[0].value = '';

            this.departInfo.arr.push(param);
          }
        }).catch((error) => {
          this.$message.error(error.message);
        });
      },

      /* 监听日期改变 */
      changeDate(code) {
        let arr = this.yearMonthList.arr;
        this.yearMonthList.val = arr.find((item) => { return (item.value === code); });

        this.updatePage(1);
      },

      /* 监听 一级下拉改变 */
      typeChange(value) {
        let arr = this.departInfo.arr;
        this.departInfo.index = arr.findIndex((item) => { return item.value === value });

        this.searchQuery();
      },

      /* 监听 二级下拉改变 */
      departChange(value) {
        let departInfo = this.departInfo;
        let arr = departInfo.arr;
        let index = departInfo.index;
        this.departInfo.chIndex = arr[index]['children'].findIndex((item) => { return item.value === value });

        this.searchQuery();
      },

      /* 监听页码改变 */
      changePage(pageNo) {
        let t = this;
        t.updatePage(pageNo);
        // 如果当前页面数据没有修改
      /*  if (t.disabled.saveOrCancel) {
          t.updatePage(pageNo);
          return;
        }

        t.$confirm({
          title: '当前页面数据有修改，是否仍要进行跳转？',
          onOk() { t.updatePage(pageNo); },
          onCancel() {
            t.queryParam.pageNo = pageNo;

            // 点击取消后，将当前页码还原成上一次的页码
            setTimeout(() => { t.queryParam.pageNo = t.resData.current; }, 70);
          }
        });*/
      },

      /* 监听分页条数的改变 */
      onShowSizeChange(current, pageSize) {
        this.queryParam.pageSize = pageSize;
        this.queryParam.pageNo = 1;

        if (this.tableData.dataSource.length > 0) {
          this.searchQuery();
        }
      },

      /* 更新页面数据 */
      updatePage(pageNo) {
        this.queryParam.pageNo = pageNo;
        this.searchQuery();
      },

      /* 查询 */
      searchQuery() {
        let t = this;

        t.loading = true;
        t.tableData.dataSource = [];
        t.initDisabled();

        // 获取总经理评分进度
        if (this.k === 'gm') { this.getGmGradedRadio(); }

        // 组装接口需要的参数
        let departInfo = t.departInfo;
        let departVal = departInfo.arr[departInfo.index].value || null;
        let children = departInfo.arr[departInfo.index]['children'];
        let params = {
          indexYearMonth: this.yearMonthList.val.value,   // 日期格式 YYYYMM
          indexGroup    : departVal,                      // 部门类别
          indexDepart   : departVal ? (children[departInfo.chIndex].value || null) : null,   // 部门编码
          pageNo        : t.queryParam.pageNo,            // 页数
          pageSize      : t.queryParam.pageSize,          // 每页返回多少条数据

          ...t.orderBy,     // 排序
        }

        /* 获取评分列表 */
        apiConfig[this.k].getData(params).then((res) => {
          t.loading = false;
          let resData = res.result;

          if (!resData || (resData && resData.records && resData.records.length === 0)) {
            t.resData = t.tableData.dataSource = [];
            t.queryParam.pageNo = 1;
          } else {
            t.resData = JSON.parse(JSON.stringify(resData));  // 备份
            t.tableData.dataSource = resData.records;         // 更新列表
            t.queryParam.pageNo = resData.current;            // 更新页数
          }

          t.initDisabled();
        }).catch((error) => {
          t.loading = false;
          this.$message.error(error.message);
        });
      },

      /* 只有【总经理评分】需要获取评分进度 */
      getGmGradedRadio() {
        let params = {
          indexYearMonth: this.yearMonthList.val.value
        }

        apiConfig[this.k].getProgress(params).then((res) => {
          if (!res.success) {
            this.$message.warning(res.message);
            return;
          }

          this.speedInfo = res.result;
        }).catch((error) => {
          this.speedInfo = {};
          this.$message.error(error.message);
        });
      },

      /**
       * 显示评分进度
       * 1. 必须是总经理评分模块
       * 2. 并且接口返回数值
       * */
      showSpeed() {
        if (this.k !== 'gm') { return false; }

        let speedInfo = this.speedInfo;
        if (!speedInfo) { return false; }
        return (typeof speedInfo.needCount === 'number') || (typeof speedInfo.editedCount === 'number');
      },

      /* 显示评分参考 */
      showRefModal(record) {
        let indexDepartName = record.indexDepartName;
        let indexScorerName = '(' + record.indexScorerName + ')';
        this.modalInfo = {
          show: true,
          title: '被评部门「' + indexDepartName + indexScorerName + '」评分参考',
          date: this.yearMonthList.val.value,
          departInfo: record
        }

        // 通知弹窗组件更新数据
        setTimeout(() => { this.$refs.scoreRef.initData(1); }, 10);
      },

      /* 取消编辑 */
      cancel() {
        this.tableData.dataSource = JSON.parse(JSON.stringify(this.resData.records));
        this.upDatas('cancel');
      },

      /* 保存数据 saveData 在 api config 中配置 */
      saveData() {
        let data = this.gradeModalInfo.date;
        if(data.grade===''){
          this.$message.warning('评分不能为空，请合法打分！');
          return;
        }
        if(data.scoreComments.length<=0){
          if(data.grade!=0){
            this.$message.warning('必须添加评分事项！');
            return;
          }

        }
        if(data.scoreComments.length>=0 && data.grade!=0){
          for (let i in data.scoreComments) {
            if(data.scoreComments[i].code===''){
              this.$message.warning('评分事项不能为空！');
              return;
            }else if(data.scoreComments[i].content===''){
              this.$message.warning('评分意见不能为空！');
              return;
            }
          }
        }else {
          for (let i in data.scoreComments) {
            if (data.scoreComments[i].code === '' && data.scoreComments[i].content === '') {
              data.scoreComments.splice(i)          }
          }
        }



        this.submitData('saveData'); },

      /* 得分计算 calcScores 在 api config 中配置 */
      kaGradeCalc() { this.submitData('calcScores'); },

//督办事项查看
      getSysConfig(){
        apiConfig.common.getSysConfig().then((res) => {
          this.superviseItem = res.result;
          if(this.superviseItem!=null){
            window.open(this.superviseItem.configBody);
          }else{

            this.$message.info("暂时无法访问，请联系管理员！");
          }
        }).catch((error) => {
          this.$message.error(error.message);
        });
      },



      /* 返回接口需要的数组 */
      getParamArr() {
        let arr = [];
        let records = this.resData.records;           // 源数据
        let dataSource = this.tableData.dataSource;   // 展示数据
        let dataSource1 = this.gradeModalInfo.date;
        /*let changeArr = dataSource.filter((item, i) => {
          return ((item.grade != records[i].grade) || (item.indexValueComments != records[i].indexValueComments) || (item.superviseGrade != records[i].superviseGrade));
        });*/
        let changeArr=[];
        changeArr.push(dataSource1);
                /* 返回有修改的项 */
        if (changeArr.length > 0) {
          changeArr.forEach((item) => {
            arr.push({
              "id": item.id,
              "indexDepart": item.indexDepart,
              "grade": item.grade,
              "scoreComments": item.scoreComments,
              "superviseGrade": item.superviseGrade
            });
          });
        }

        return arr;
      },

      /* 保存数据 | 得分计算 */
      submitData(fn) {
        let t = this;
        t.gradeModalInfo.show = false;
        let yearMonth = this.yearMonthList.val.value;
        let params = {
          indexYearMonth: yearMonth,
          tkIndexValueVOs: this.getParamArr()
        }

        t.loading = true;
        apiConfig[this.k][fn](params).then((res) => {
          t.loading = false;

          if (!res.success) {
            t.$message.warning(res.message);
            return;
          }

          if (fn === 'saveData') {
            t.$message.success('保存成功！');

          } else {
            t.$message.success('计算成功！');
          }
          t.searchQuery();


        }).catch((error) => {
          t.loading = false;
          t.$message.error(error.message);
        });
      },

      /* 一键评分 */
      oneKeyScore() {
        this.tableData.dataSource.forEach((item) => {
          if (!item.grade) { item.grade = item.avegGrade; }     // 只将没有评分的项赋值
        });
        this.upDatas('oneKeyScore');
      },

      /* 重置是否禁用按钮 */
      initDisabled() {
        let records = this.resData.records;
        let dataSource = this.tableData.dataSource;

        // 如果数据为空，所有按钮不可点击
        if (dataSource.length === 0) {
          this.disabled = { oneKeyScore: true, saveOrCancel: true };
          return;
        }

        // 列表中，只要有一项评分为 0，并且平均分不为 0 时，就可以一键评分
        this.disabled.oneKeyScore = !(dataSource.some((item) => { return (item.grade == 0 && item.avegGrade != 0);}));

        // 保存并计算和取消按钮
        this.disabled.saveOrCancel = !(records.some((item, i) => {
          return (item.grade != dataSource[i].grade) || (item.indexValueComments != dataSource[i].indexValueComments) || (item.superviseGrade != dataSource[i].superviseGrade)
        }));
      },

      /* 更新数据 通过子组件 EditableCell 触发 */
      upData(val, k, ind) {
        if(val===""){
          this.$message.warning('请正确输入分数！');
        }else if(this.tableData.dataSource[ind][k]!=val){
            this.tableData.dataSource[ind][k] = val;
            this.initDisabled();
            this.saveData();
        }



      },

      /* 更新子组件里面的显示 */
      upDatas(str) {
        let arr = this.$refs.upDatas;
        let dataSource = this.tableData.dataSource;

        for (let i = 0; i < arr.length; i++) {
          let item = arr[i];
          if (str === 'cancel') {
            // 将子组件的数据还原
            this.$refs.upDatas[i].value = dataSource[item.ind][item.k];
          } else {
            if (item.k === 'grade' && !item.value) {
              // 一键评分赋值，取双向平均分
              this.$refs.upDatas[i].value = dataSource[item.ind].avegGrade;
            }

            // TODO 让单元格变成可编辑的输入框
            // this.$refs.upDatas[i].changeSate();
          }
        }

        this.initDisabled();
      }

    }
  }
</script>
<!-- js end -->


<!-- css start -->
<style lang="less" scoped>
  .icon-more {
    margin-left: 5px;
    color: @primary-color;
  }
  .editable-cell-icon { color: #FA541C; margin-left: 5px;}


  .menu-box {
    margin-bottom: 10px;

    [class*="query-"] {
      float: left;
      margin-right: 10px;
    }

    /deep/.ant-select {
      width: 120px;
    }
  }

  .btn-box {
    float: right;
    button { margin-left: 4px; }
  }

  .pagination-box {
    margin-top: 20px;
    float: right;
  }

  .score-ref {
    color: @primary-color;
    cursor: pointer;

    &:hover { text-decoration: underline; }
  }

  .speed-box {
    font-size: 12px;

    .speed-total,
    .speed-load {
      float: left;
      margin: 0 10px 10px 1px;
      padding: 2px 10px;
      border-radius: 2px;
    }

    .speed-total { background: #bbdfb7; }
    .speed-load { background: #fad0cc; }

    .title, .unit { color: #666666; }
    .num { font-weight: bold; font-size: 14px; }
  }

  /deep/table.ant-table-fixed {
    table-layout: fixed;
  }

  /deep/.ant-table-tbody > tr > td {
    height: 60px;
    padding-top: 2px;
    padding-bottom: 2px;
  }

  /deep/.ant-table-tbody > tr > td:nth-child(6) {
    word-wrap: break-word;
    word-break: break-all;

    /*display: -webkit-box;*/
    /*white-space: nowrap;*/
    /*overflow: hidden;*/
    /*text-overflow: ellipsis;*/
    /*-webkit-box-orient: vertical;*/
    /*-webkit-line-clamp: 2;*/
  }

  .high_light {
    color: #FF6600;
    font-weight: bold;
  }

  /deep/.ant-table-content .ant-table-body,
  /deep/.ant-table-content .ant-table-body-inner{
}
</style>
<!-- css end -->


